//
//  KeyboardViewController.swift
//  CustomKeyBoard
//
//  Created by joker on 15/7/24.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

extension UIView {
    func scaleByFactor(factor: CGFloat, animationDuration: NSTimeInterval) {
        UIView.animateWithDuration(animationDuration, animations: {[weak self] in
            let strongSelf = self!
            strongSelf.transform = CGAffineTransformMakeScale(factor, factor)
        })
    }
    func resetScalingWithAnimationDuration(duration: NSTimeInterval) {
        scaleByFactor(1.0, animationDuration: duration)
    }
    
}

class KeyboardButton: UIView {
    var button: UIButton!
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    init(buttonTitle: String) {
        super.init(frame: CGRectZero)
        button = UIButton(frame: bounds)
        button.autoresizingMask = .FlexibleWidth | .FlexibleHeight
        addSubview(button)
        button.setTitle(buttonTitle, forState: .Normal)
        button.addTarget(self, action: "enlargeForTouchDown", forControlEvents: .TouchDown)
        button.addTarget(self, action: "goToNormalSize", forControlEvents: .AllEvents ^ (.TouchDown))
    }
    
    func goToNormalSize(){
        self.resetScalingWithAnimationDuration(0.1)
    }
    func enlargeForTouchDown() {
        self.scaleByFactor(3.0, animationDuration: 0.1)
    }
}

class KeyboardView: UIView {
    var buttons = [KeyboardButton]()
    let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    var nextKeyboardButton: KeyboardButton!
    let buttonWidth = 45.0 as CGFloat
    let buttonHeight = 45.0 as CGFloat
    
    weak var textDocumentProxy: UITextDocumentProxy? {
        willSet(newValue) {
            if let proxy = newValue {
                if proxy.keyboardAppearance! == .Dark {
                    backgroundColor = UIColor.darkGrayColor()
                } else {
                    backgroundColor = UIColor.lightGrayColor()
                }
            }
        }
    }
    
    required init(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect){
        super.init(frame: frame)
        backgroundColor = UIColor.lightGrayColor()
        
        for character in characters {
            let keyboardButton = KeyboardButton(buttonTitle: "\(character)")
            buttons.append(keyboardButton)
            keyboardButton.button.addTarget(self, action: "handleTapOnButton:",forControlEvents: .TouchUpInside)
            addSubview(keyboardButton)
        }
        
        let backspaceButton = KeyboardButton(buttonTitle: "<")
        backspaceButton.button.addTarget(self, action: "handleBackSpace", forControlEvents: .TouchUpInside)
        
        buttons.append(backspaceButton)
        addSubview(backspaceButton)
        
        
        nextKeyboardButton = KeyboardButton(buttonTitle: "->")
        nextKeyboardButton.button.addTarget(self, action: "goToNextKeyboard", forControlEvents: .TouchUpInside)
        buttons.append(nextKeyboardButton)
        addSubview(nextKeyboardButton)
    }
    func handleBackSpace(){
        if let proxy = textDocumentProxy {
            proxy.deleteBackward()
        }
    }
    func goToNextKeyboard(){
        println("goToNextKeyborad() is called!")
    }
    func handleTapOnButton(button: UIButton){
        let buttonText = button.titleForState(.Normal)
        if let text = buttonText {
            if let proxy = textDocumentProxy {
                proxy.insertText(text)
            }
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        var xPosition = 0.0 as CGFloat
        var yPosition = 0.0 as CGFloat
        
        for button in buttons {
            button.frame = CGRect(x: xPosition, y: yPosition, width: buttonWidth, height: buttonHeight)
            
            xPosition += buttonWidth
            
            if xPosition + buttonWidth >= bounds.size.width {
                xPosition = 0.0
                yPosition += buttonHeight
            }
        }
    }
}
class KeyboardViewController: UIInputViewController {

    override func loadView() {
        let loadedView = KeyboardView(frame:CGRectZero)
        loadedView.textDocumentProxy = (textDocumentProxy as! UITextDocumentProxy)
        loadedView.nextKeyboardButton.button.addTarget(self,action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
        view = loadedView
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated
    }

    override func textWillChange(textInput: UITextInput) {
        // The app is about to change the document's contents. Perform any preparation here.
    }


}
